import { View, Text, ScrollView } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import {
  Form,
  Cell,
  Input,
  Button,
  Dialog,
  Toast,
  FloatingBubble,
  Tabs,
  Popup,
  Checkbox,
  Image,
} from "@taroify/core";

import HeaderSearch from "@/components/HeaderSearch/index";
import Header from "@/components/Header/index";
import Footer from "@/components/Footer/index";
import GoodsTitle from "@/components/GoodsTitle/index";
import { requestPOST } from "@/request";
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setShopInfo, setUserInfo } from "@/store/reducers/userInfo";
import { RootState } from "@/store";
import { setBusinessInfo, setHomeShow } from "@/store/reducers/businessInfo";
import { setBusinessCategory } from "@/store/reducers/commonCategory";
import { ArrowUp } from "@taroify/icons";

export default function Index() {
  const dispatch = useDispatch();
  const [form, setForm] = useState({
    email: "czetouch@gmail.com",
    password: "123456",
  });
  const token = useSelector((state: RootState) => state.userInfo.token);
  const shopInfo = useSelector((state: RootState) => state.userInfo.shopInfo);
  const userInfo = useSelector((state: RootState) => state.userInfo.userInfo);
  const homeShow = useSelector((state: RootState) => state.business.isHomeShow);
  const [read, setRead] = useState(false);
  const [open, setOpen] = useState(false);
  const [info, setInfo] = useState<any>({});
  const [model, setModel] = useState(false);
  const [img, setImage] = useState("");

  const getImage = () => {
    requestPOST("other/getCodeImage").then((res) => {
      setImage(process.env.TARO_APP_API + res);
    });
  };

  const getHelpInfo = () => {
    requestPOST("other/personalAccountHelp").then((res: any) => {
      setInfo({
        ...res,
        agreement_business: res.agreement_business
          .replaceAll("&nbsp;", " ")
          .replaceAll(
            "https://etouch1api.etouch-b2b.com",
            process.env.TARO_APP_API
          ),
      });
    });
  };

  const onSubmit = () => {
    requestPOST("other/loginByEmail", { ...form }).then((res: any) => {
      if (res.userType !== 2) {
        return Toast.open({ type: "fail", message: "该用户暂无权限" });
      }
      Taro.setStorageSync("token", res.token);
      Taro.setStorageSync("userInfo", res);
      if (res.userType === 2) {
        dispatch(setUserInfo(res));
        getShopInfo();
      } else {
        getUserInfo(res);
      }
      formRef.current?.reset();
    });
  };

  const getShopInfo = () => {
    requestPOST("shop/shopMyInfo").then((res: any) => {
      dispatch(setShopInfo(res));
      getBuinesCategoryList(res.businessId);
      requestPOST(`other/businessIntroduction/${res.businessId}`).then(
        (res1: any) => {
          requestPOST(`other/businessAppraiseList/${res.businessId}`, {
            businessId: res.businessId,
            isPage: 1,
            pageNum: 1,
            pageSize: 5,
            pageTotal: 0,
          }).then((res2: any) => {
            dispatch(
              setBusinessInfo({
                id: res.businessId,
                info: { ...res, ...res1, ...res2 },
              })
            );
            dispatch(setHomeShow(true));
          });
        }
      );
    });
  };

  const getUserInfo = (res1) => {
    requestPOST("consumer/myInfo").then((res: any) => {
      dispatch(setUserInfo({ ...res1, ...res }));
      if (res?.accountType == 2) {
        getShowList();
      }
    });
  };

  const getBuinesCategoryList = (businessId) => {
    requestPOST(`shop/shopCategoryList/${businessId}`).then((res: any) => {
      let nav = [
        { categoryName: "Home", id: 1 },
        { categoryName: "Company Overview", id: 2 },
        { categoryName: "Ratings & Reviews", id: 5 },
        { categoryName: "Feedback", id: 3 },
        { categoryName: "ContactUs", id: 4 },
        ...res,
      ];
      dispatch(setBusinessCategory(nav));
    });
  };

  const exit = () => {
    Dialog.confirm({
      title: "标题",
      message: "你确定要退出吗？",
      backdrop: {
        style: { zIndex: 10000 },
      },
      style: {
        zIndex: 10001,
      },
      onConfirm: () => {
        dispatch(setHomeShow(false));
        dispatch(setBusinessInfo({ id: "", info: {} }));
        dispatch(setUserInfo({}));
        Taro.setStorageSync("token", "");
        Taro.setStorageSync("userInfo", "");
      },
    });
  };

  const [scrollTop, setScrollTop] = useState(0);

  const onClick = () => {
    setScrollTop(0);
    setTimeout(() => {
      setScrollTop(Math.random());
    }, 1);
  };

  useDidShow(() => {
    if (token) {
      if (homeShow) {
        dispatch(setHomeShow(false));
      }

      Taro.nextTick(() => {
        getShopInfo();
      });
    }
  });

  const formRef = useRef<any>();

  const [showList, setShowList] = useState<any>({
    childBusinessCoupon: 1,
    childBusinessIntroduct: 1,
    childBusinessQualification: 1,
    childBusinessPayType: 1,
    childBusinessPdocutType: 1,
    childBusinessProduct: 1,
    childBusinessOrder: 1,
    childBusinessInquirycenter: 1,
    childBusinessFeedback: 1,
    childBusinessContactUs: 1,
    childBusinessShopCart: 1,
    childBusinessPromotion: 1,
    childBusinessOtherSystem: 1,
  });

  const getShowList = () => {
    requestPOST("shop/getNowChildBusinessPermissionsInfo").then((res: any) => {
      setShowList({ ...res });
    });
  };

  useEffect(() => {
    if (userInfo?.accountType == 2) {
      getShowList();
    }
    getHelpInfo();
    getImage();
  }, []);

  const handleRead = () => {
    setOpen(false);
    setRead(true);
  };

  const wxCode = useRef<any>("");
  const wxOpenId = useRef<any>("");
  const wxPhone = useRef<any>("");

  const handleGetPhoneNumber = (e: any) => {
    Taro.login({
      success({ code }) {
        wxCode.current = code;
        const { iv, encryptedData, errMsg } = e.detail;
        try {
          if (!wxCode) {
            Toast.open("code为空");
            return;
          }
          if (errMsg.includes("ok")) {
            Taro.showLoading({
              title: "正在登录...",
            });
            requestPOST(`thirdParty/getOpenIdByCode/${wxCode.current}`).then(
              (res: any) => {
                const { session_key, openid } = res;
                wxOpenId.current = openid;
                requestPOST("thirdParty/getWxPhoneDecrypt", {
                  iv,
                  encryptedData,
                  sessionKey: session_key,
                }).then((res1: any) => {
                  wxPhone.current = res1.phoneNumber;
                  isBindEmail();
                });
              }
            );
          }
        } catch (err) {}
      },
    });
  };

  const isBindEmail = () => {
    requestPOST("thirdParty/judeWxIsBindEmail", {
      wxOpenId: wxOpenId.current,
      wxPhone: wxPhone.current,
    }).then((res: any) => {
      if (res) {
        setForm4({
          email: res,
          code: "123",
        });
        wxLogin();
      } else {
        setOpen1(true);
        Taro.hideLoading();
      }
    });
  };

  const [form4, setForm4] = useState({
    email: "",
    code: "",
  });
  const [time1, setTime1] = useState<number>(0);
  const formRef1 = useRef<any>();
  const [open1, setOpen1] = useState(false);

  let timer;
  const sendEmailCode = () => {
    if (!form4.email) {
      return Toast.open({ type: "fail", message: "请输入邮箱" });
    }
    requestPOST(`thirdParty/sendBindWxEmailCode/${form4.email}`).then(() => {
      Toast.open({ type: "success", message: "发送成功" });
      let time = 60;
      timer = setInterval(() => {
        if (time <= 0) {
          clearInterval(timer);
        }
        setTime1(--time);
      }, 1000);
    });
  };

  const onSubmit4 = () => {
    if (!form4.email) {
      return Toast.open({ type: "fail", message: "请输入邮箱" });
    }
    if (!form4.code) {
      return Toast.open({ type: "fail", message: "请输入验证码" });
    }
    Taro.showLoading({
      title: "绑定中...",
    });
    wxLogin();
  };

  const wxLogin = () => {
    Taro.login({
      success({ code }) {
        requestPOST("thirdParty/wxXcxLogin", {
          wxCode: code,
          wxOpenId: wxOpenId.current,
          wxPhone: wxPhone.current,
          bindEmail: form4.email,
          bindJudeCode: form4.code,
        })
          .then((res: any) => {
            setOpen1(false);
            Toast.open({ type: "success", message: "登录成功" });
            clearForm4();
            Taro.setStorageSync("token", res.token);
            Taro.setStorageSync("userInfo", res);
            if (res.userType === 2) {
              dispatch(setUserInfo(res));
              getShopInfo();
            } else {
              getUserInfo(res);
            }
          })
          .finally(() => {
            Taro.hideLoading();
          });
      },
    });
  };

  const clearForm4 = () => {
    setForm4({
      email: "",
      code: "",
    });
    formRef1.current?.reset();
  };

  const handleGetPhoneNumber1 = (e) => {
    Taro.login({
      success({ code }) {
        const { iv, encryptedData, errMsg } = e.detail;
        try {
          if (!code) {
            Toast.open("code为空");
            return;
          }
          if (errMsg.includes("ok")) {
            Taro.showLoading({ title: "绑定中..." });
            requestPOST(`thirdParty/getOpenIdByCode/${code}`).then(
              (res: any) => {
                const { session_key, openid } = res;
                requestPOST("thirdParty/getWxPhoneDecrypt", {
                  iv,
                  encryptedData,
                  sessionKey: session_key,
                }).then((res1: any) => {
                  const { phoneNumber } = res1;
                  Taro.login({
                    success({ code }) {
                      requestPOST("shop/businessBindWx", {
                        wxCode: code,
                        wxOpenId: openid,
                        wxPhone: phoneNumber,
                      })
                        .then(() => {
                          Toast.open({ type: "success", message: "绑定成功" });
                        })
                        .finally(() => {
                          Taro.hideLoading();
                        });
                    },
                  });
                });
              }
            );
          }
        } catch (err) {}
      },
    });
  };

  return (
    <ScrollView
      className="taroContainer"
      enable-passive={true}
      scroll-y={true}
      scrollWithAnimation
      scrollTop={scrollTop}
    >
      <FloatingBubble
        className="taroify-floating-bubble1"
        icon={<ArrowUp />}
        onClick={onClick}
        axis="lock"
      />
      <HeaderSearch />
      <Header isHome={true} />
      {!token && (
        <View>
          <GoodsTitle title="Login to your account" isMore={false} />
          <View style={{ margin: "40px 0" }}>
            <Tabs>
              <Tabs.TabPane title="手机号快捷登录">
                <View style={{ padding: "20px" }}>
                  <Button
                    openType="getPhoneNumber"
                    onGetPhoneNumber={handleGetPhoneNumber}
                    color="primary"
                    shape="round"
                    block
                    disabled={!read}
                  >
                    手机号快捷登录
                  </Button>
                </View>
              </Tabs.TabPane>
              <Tabs.TabPane title="账号密码登录">
                <Form
                  ref={formRef}
                  onSubmit={onSubmit}
                  style={{ marginTop: "20px" }}
                >
                  <Cell.Group inset>
                    <Form.Item
                      name="email"
                      rules={[
                        {
                          required: true,
                          message: "Please fill in your email address",
                        },
                      ]}
                    >
                      <Form.Label>email</Form.Label>
                      <Form.Control>
                        <Input
                          onChange={(e) =>
                            setForm({ ...form, email: e.detail.value })
                          }
                          placeholder="Please fill in your email address"
                        />
                      </Form.Control>
                    </Form.Item>
                    <Form.Item
                      name="password"
                      rules={[
                        {
                          required: true,
                          message: "Please enter your login password",
                        },
                      ]}
                    >
                      <Form.Label>password</Form.Label>
                      <Form.Control>
                        <Input
                          onChange={(e) =>
                            setForm({ ...form, password: e.detail.value })
                          }
                          password
                          placeholder="Please enter your login password"
                        />
                      </Form.Control>
                    </Form.Item>
                  </Cell.Group>
                  <View style={{ padding: "20px 14px" }}>
                    <Button
                      block
                      color="primary"
                      formType="submit"
                      disabled={!read}
                    >
                      Login
                    </Button>
                  </View>
                </Form>
                {/* <View
                  style={{
                    padding: "14px",
                    fontSize: "13px",
                    textAlign: "center",
                  }}
                >
                  <Text>Dont have an account ? </Text>
                  <Text
                    style={{ color: "#13af87", fontWeight: "bold" }}
                    onClick={() =>
                      Taro.navigateTo({ url: "/packages/register/index" })
                    }
                  >
                    Register Now
                  </Text>
                </View> */}
                <View
                  style={{
                    padding: "14px",
                    fontSize: "13px",
                    textAlign: "center",
                  }}
                >
                  <Text>Forget the password ? </Text>
                  <Text
                    style={{ color: "#13af87", fontWeight: "bold" }}
                    onClick={() => setModel(true)}
                  >
                    Contact customer service
                  </Text>
                </View>
              </Tabs.TabPane>
            </Tabs>
            <View
              style={{
                padding: "14px 30px",
                fontSize: "13px",
                display: "flex",
                gap: "5px",
              }}
            >
              <Checkbox
                checked={read}
                onChange={setRead}
                style={{ flex: "0 0 20px" }}
                shape="square"
                size={13}
              />
              <View>
                <Text>已阅读并同意协议</Text>
                <Text
                  style={{ color: "rgb(19, 175, 135)", cursor: "pointer" }}
                  onClick={() => setOpen(true)}
                >
                  《Ongooshop供应商注册协议》
                </Text>
                <Text>，允许平台统一管理本人账号信息 </Text>
              </View>
            </View>
          </View>
        </View>
      )}
      {token && userInfo.userType == 2 && (
        <View>
          <View
            style={{
              height: "150px",
              backgroundColor: "#13af87",
              borderRadius: "0 0 50% 50%",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              gap: "10px",
              color: "#fff",
            }}
          >
            <View>Hi,{shopInfo.userName}!</View>
            <View>付费会员</View>
            <Button
              variant="outlined"
              color="default"
              size="small"
              shape="round"
              style={{ color: "#fff" }}
              onClick={() => exit()}
            >
              exit
            </Button>
          </View>
          <View>
            <Cell
              title="基本信息"
              isLink
              onClick={() =>
                Taro.navigateTo({ url: "/packages1/basicInfo/index" })
              }
            />
            {Boolean(showList?.childBusinessIntroduct) && (
              <Cell
                title="企业简介"
                isLink
                onClick={() =>
                  Taro.navigateTo({ url: "/packages1/company/index" })
                }
              />
            )}
            {Boolean(showList?.childBusinessQualification) && (
              <Cell
                title="企业资质"
                isLink
                onClick={() =>
                  Taro.navigateTo({ url: "/packages1/enterprise/index" })
                }
              />
            )}
            {Boolean(showList?.childBusinessPdocutType) && (
              <Cell
                title="产品分类"
                isLink
                onClick={() =>
                  Taro.navigateTo({ url: "/packages1/class/index" })
                }
              />
            )}
            {Boolean(showList?.childBusinessProduct) && (
              <Cell
                title="产品管理"
                isLink
                onClick={() =>
                  Taro.navigateTo({ url: "/packages1/goodsInfo/index" })
                }
              />
            )}
            {Boolean(showList?.childBusinessOrder) && (
              <Cell
                title="订单信息"
                isLink
                onClick={() =>
                  Taro.navigateTo({ url: "/packages1/orderInfo/index" })
                }
              />
            )}

            {Boolean(showList?.childBusinessInquirycenter) && (
              <Cell
                title="询盘中心"
                isLink
                onClick={() =>
                  Taro.navigateTo({ url: "/packages1/inquiry/index" })
                }
              />
            )}
            {Boolean(showList?.childBusinessFeedback) && (
              <Cell
                title="客户反馈"
                isLink
                onClick={() =>
                  Taro.navigateTo({ url: "/packages1/feedback/index" })
                }
              />
            )}
            {Boolean(showList?.childBusinessContactUs) && (
              <Cell
                title="联系方式管理"
                isLink
                onClick={() =>
                  Taro.navigateTo({ url: "/packages1/contact/index" })
                }
              />
            )}
            {Boolean(showList?.childBusinessShopCart) && (
              <Cell
                title="购物车管理"
                isLink
                onClick={() =>
                  Taro.navigateTo({ url: "/packages1/goods/index" })
                }
              />
            )}

            {Boolean(showList?.childBusinessPromotion) && (
              <Cell
                title="推广人员"
                isLink
                onClick={() => {
                  Taro.navigateTo({ url: "/packages1/staff/index" });
                }}
              />
            )}
            <Cell
              title="应用市场"
              isLink
              onClick={() =>
                Taro.navigateTo({ url: "/packages1/application/index" })
              }
            />
            {showList?.childBusinessOtherSystem && (
              <Cell
                title="易速贸数据管家"
                isLink
                onClick={() =>
                  Taro.navigateTo({ url: "/packages1/datam/index" })
                }
              />
            )}

            <Cell
              title="帮助中心"
              isLink
              onClick={() =>
                Taro.navigateTo({ url: "/packages/helpCenter/index" })
              }
            />
            <View style={{ padding: "20px" }}>
              <Button
                color="primary"
                block
                openType="getPhoneNumber"
                onGetPhoneNumber={handleGetPhoneNumber1}
              >
                绑定
              </Button>
            </View>
          </View>
        </View>
      )}
      {token && userInfo.userType != 2 && (
        <View>
          <View
            style={{
              height: "150px",
              backgroundColor: "#13af87",
              borderRadius: "0 0 50% 50%",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              gap: "10px",
              color: "#fff",
            }}
          >
            <View>Hi,{userInfo.userName}!</View>
            <Button
              variant="outlined"
              color="default"
              size="small"
              shape="round"
              style={{ color: "#fff" }}
              onClick={() => exit()}
            >
              exit
            </Button>
          </View>
        </View>
      )}
      <View>
        <Footer />
      </View>

      <Popup
        open={open1}
        placement="center"
        style={{ height: "auto" }}
        rounded
        lock={false}
      >
        <View style={{ width: "90vw", padding: "14px 0" }}>
          <View style={{ fontWeight: 700, margin: "10px 16px" }}>绑定邮箱</View>
          <Form ref={formRef1} defaultValues={form4} onSubmit={onSubmit4}>
            <Cell.Group inset>
              <Form.Item name="email">
                <Form.Label>邮箱</Form.Label>
                <Form.Control>
                  <Input
                    value={form4.email}
                    onChange={(e) =>
                      setForm4({ ...form4, email: e.detail.value })
                    }
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item name="code">
                <Form.Label>验证码</Form.Label>
                <Form.Control>
                  <Input
                    value={form4.code}
                    password
                    onChange={(e) =>
                      setForm4({ ...form4, code: e.detail.value })
                    }
                  />
                  <Button
                    disabled={time1 > 0}
                    onClick={() => sendEmailCode()}
                    color="primary"
                    size="small"
                  >
                    {time1 > 0 ? time1 + "s" : "获取验证码"}
                  </Button>
                </Form.Control>
              </Form.Item>
            </Cell.Group>
            <View style={{ margin: "1rem", display: "flex", gap: "20px" }}>
              <Button
                shape="round"
                color="primary"
                block
                variant="outlined"
                onClick={() => {
                  setOpen1(false);
                  clearForm4();
                }}
              >
                取消
              </Button>
              <Button shape="round" color="primary" block formType="submit">
                绑定
              </Button>
            </View>
          </Form>
        </View>
      </Popup>

      <Dialog
        open={open}
        onClose={setOpen}
        backdrop={{ style: { zIndex: 10000 } }}
        style={{ zIndex: 10001 }}
      >
        <Dialog.Header>{info.agreement_business_name}</Dialog.Header>
        <Dialog.Content>
          <ScrollView style={{ height: "60vh" }} scrollY>
            <View
              style={{ textAlign: "left" }}
              dangerouslySetInnerHTML={{ __html: info.agreement_business }}
            ></View>
          </ScrollView>
        </Dialog.Content>
        <Dialog.Actions>
          <Button onClick={() => handleRead()}>我已阅读</Button>
        </Dialog.Actions>
      </Dialog>

      <Dialog
        open={model}
        onClose={setModel}
        backdrop={{ style: { zIndex: 10000 } }}
        style={{ zIndex: 10001 }}
      >
        <Dialog.Header>Contact Customer Service</Dialog.Header>
        <Dialog.Content>
          <View
            style={{
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
              gap: "15px",
            }}
          >
            <Image src={img} width={151} height={151} mode="aspectFill" />
            <View>Scan QR code to contact us</View>
          </View>
        </Dialog.Content>
        <Dialog.Actions>
          <Button onClick={() => setModel(false)}>关闭</Button>
        </Dialog.Actions>
      </Dialog>
    </ScrollView>
  );
}
